package com.baizhi.controller;

import cn.hutool.captcha.LineCaptcha;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author yu
 */
@RestController
@Slf4j
public class CommonController {
    private final String BUCKETNAME = "bzmall-yuhao";
    @Autowired
    private OSS ossClient;
    @RequestMapping("/getValidate")
    public void getValidate(HttpServletResponse response, HttpSession session) throws IOException {
        LineCaptcha lineCaptcha = new LineCaptcha(100, 50);
        String trueValidateCode = lineCaptcha.getCode();
        session.setAttribute("trueValidateCode",trueValidateCode);
        log.info(trueValidateCode);
        ServletOutputStream outputStream = response.getOutputStream();
        lineCaptcha.write(outputStream);
    }
    @RequestMapping("/file/upload")
    public Map upload(MultipartFile pic, HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/img");
        String originalFilename = pic.getOriginalFilename();
        FileOutputStream outputStream = new FileOutputStream(realPath +"/"+originalFilename);
        InputStream inputStream = pic.getInputStream();
        FileCopyUtils.copy(inputStream,outputStream);
        HashMap<String, String> map = new HashMap<>();
        map.put("status","success");
        map.put("path","/img/"+pic.getOriginalFilename());
        return map;
    }

    @RequestMapping("/file/ossUpload")
    public Map ossUploadFile(@RequestBody MultipartFile file) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        String bucketName = BUCKETNAME;
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String type = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName= "logo/"+ UUID.randomUUID().toString().substring(0,9)+type;
        PutObjectResult putObjectResult = ossClient.putObject(BUCKETNAME, objectName, inputStream);
        map.put("status","success");
        map.put("path","https://bzmall-yuhao.oss-cn-beijing.aliyuncs.com/"+objectName);
        return map;
    }
}
